package com.tan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tan.domain.Blog;
import com.tan.domain.Comment;
import com.tan.domain.User;
import com.tan.domain.vo.CommentVO;
import com.tan.mapper.CommentMapper;
import com.tan.service.BlogService;
import com.tan.service.CommentService;
import com.tan.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
        implements CommentService {
    @Autowired
    UserService userService;
    @Autowired
    BlogService blogService;
    @Autowired
    CommentMapper commentMapper;

    @Override
    public List<CommentVO> getCommentsByBlogId(Long blogId) {

        LambdaQueryWrapper<Comment> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Comment::getBlogId, blogId);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        List<CommentVO> commentVOS = new LinkedList<>();
        comments.forEach(e->{
            CommentVO vo = new CommentVO();
            BeanUtils.copyProperties(e,vo);
            commentVOS.add(vo);
        });
        commentVOS.forEach(e -> {
            Blog blog = e.getBlog();
            blog.setContent("");
            e.setBlog(blog);
        });
        return commentVOS.stream().sorted(Comparator.comparing(CommentVO::getCreateTime).reversed()).collect(Collectors.toList());
    }

    @Override
    public CommentVO addComment(Map<String, Object> para) {
        String content = String.valueOf(para.get("content"));
        Long blogId = Long.parseLong(para.get("blogId").toString());
        Long userId = Long.parseLong(para.get("userId").toString());
        long parentId = Long.parseLong(para.get("parentId").toString());
        User user = userService.getById(userId);
        CommentVO comment = new CommentVO();
        comment.setContent(content);
        comment.setBlogId(blogId);
        comment.setBlog(blogService.getById(blogId));
        comment.setUserId(userId);
        comment.setParentCommentId(parentId);
        comment.setNickname(user.getNickname());
        comment.setEmail(user.getEmail());
        comment.setAvatar(user.getAvatar());
        comment.setAdminComment(user.getType().equals("1"));
        if (parentId != -1) {
            comment.setParentComment(commentMapper.selectById(parentId));
        }
        comment.setCreateTime(new Date());
        commentMapper.insert(comment);
        return comment;
    }
}




